#!/bin/sh

# build script for dxvk

# Copyright 2021-2022 orbea
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

set -euf

cd -- "$(cd -- "${0%/*}/" && pwd -P)"

PRGNAM=dxvk
VERSION=${VERSION:-1.10.2}
URL="https://github.com/doitsujin/$PRGNAM/archive/v$VERSION/$PRGNAM-$VERSION.tar.gz"

. ../../functions

PKG="$HOME"/games/tools/$PRGNAM
SRC="$TARSRC"/$PRGNAM-$VERSION.tar.gz
TMP="$TMP"/$PRGNAM

_download "$SRC" "$PRGNAM-$VERSION.tar.gz" "$URL"

rm -rf -- "$TMP"
mkdir -p -- "$TMP"
cd -- "$TMP"
tar xvf "$SRC"
cd -- "$PRGNAM-$VERSION"

_flags meson

if _exists i686-w64-mingw32-g++ x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
  arch='32 64'
elif _exists i686-w64-mingw32-g++ >/dev/null 2>&1; then
  arch=32
elif _exists x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
  arch=64
else
  _die 1 'ERROR: mingw-w64 is not installed.'
fi

eval "set -- $arch"

for bin do
  CFLAGS="$BLDFLAGS" \
  CXXFLAGS="$BLDFLAGS" \
  _meson "$TMP"/build$bin \
    --libdir=share/$PRGNAM/x$bin \
    --bindir=share/$PRGNAM/x$bin \
    --cross-file=build-win$bin.txt
done

mkdir -p -- "$DST$PKG"/bin

cat > "$DST$PKG"/bin/setup_$PRGNAM<<EOF
#!/bin/sh

set -eu

d3d10=
dxgi=
install=

while [ \$# -gt 0 ]; do
  option="\$1"
  shift

  case "\$option" in
    -- )
      break
    ;;
    --with-d3d10 )
      d3d10="\$option"
    ;;
    --without-dxgi )
      dxgi="\$option"
    ;;
    install|uninstall )
      install="\$option"
    ;;
    * )
      printf '%s\\n' "Unrecognized option '\$option'." >&2
      exit 1
    ;;
  esac
done

$DST$PKG/share/$PRGNAM/setup_$PRGNAM.sh "\$install" --symlink \$d3d10 \$dxgi
EOF

cp setup_$PRGNAM.sh "$DST$PKG"/share/$PRGNAM
chmod 0755 "$DST$PKG"/share/$PRGNAM/setup_$PRGNAM.sh
chmod 0755 "$DST$PKG"/bin/setup_$PRGNAM

_install_strip "$PRGNAM" "$VERSION" "$PKG" "$TMP/$PRGNAM-$VERSION" LICENSE \
  README.md

exit 0
